import _ from 'lodash'
import type { App } from 'vue'
import { createRouter, createWebHashHistory } from 'vue-router'
import { resetRouter, buildRouter } from './router-helper'
import eventEmitter from '@/lib/event-emitter'
import Layout from '@/layout/index.vue'
import { PAGE_PATH_404, LoginConst, HomeConst } from '@/constants/system/router-const'
import { LocalStorageKeyConst } from '@/constants/framework/local-storage-key-const'
import { useStorage } from '@/hooks/web/use-storage-hook'
import { useUserStore } from '@/store/modules/user-store'
import { loginApi } from '@/api/system/login-api'

// 使用import.meta.globEager动态导入business、support、system文件夹下的所有路由
const routes = _(import.meta.glob(['./system/*.ts', './business/*.ts', './support/*.ts'], { import: 'default', eager: true }))
  .values()
  .flatten()
  .value()

const { getStorage, setStorage } = useStorage()
const router = createRouter({
  history: createWebHashHistory(),
  strict: true,
  routes,
  scrollBehavior: () => ({ left: 0, top: 0 })
})

// 路由事件发布
eventEmitter.on('Router:reload', (menuInfo?: any[]) => {
  // 重置路由
  resetRouter(router)

  // 获取后台路由数据
  const menuList = menuInfo ? menuInfo : getStorage(LocalStorageKeyConst.USER_MENU_TREE) || []

  // 添加路由
  router.addRoute({
    path: '/',
    meta: {},
    component: Layout,
    children: buildRouter(menuList)
  })
})

eventEmitter.emit('Router:reload')
// 导航守卫
router.beforeEach((to, from, next) => {
  eventEmitter.emit('Nprogress:start')
  // 公共页面，任何时候都可以跳转
  if (to.name === PAGE_PATH_404) {
    next()
    return false
  }

  // 验证登录
  const token = getStorage(LocalStorageKeyConst.USER_TOKEN)
  if (!token) {
    useUserStore().logout()
    if (to.path === LoginConst.LOGIN_PAGE_PATH) {
      next()
    } else {
      next({ path: LoginConst.LOGIN_PAGE_PATH })
    }
    return
  }

  // 登录页，则跳转到首页
  if (to.path === LoginConst.LOGIN_PAGE_PATH) {
    next({ path: HomeConst.HOME_PAGE_PATH })
    return
  }

  // 首页（ 需要登录 ，但不需要验证权限）
  if (to.path === HomeConst.HOME_PAGE_NAME) {
    next()
    return
  }

  // 设置tagNav
  useUserStore().setTagNav(to, from)

  // 设置keepAlive
  if (to.meta.keepAlive) {
    nextTick(() => {
      useUserStore().pushKeepAliveIncludes(to.meta.componentName)
    })
  }

  next()
})
router.afterEach(() => {
  eventEmitter.emit('Nprogress:done')
})

export async function setupRouter(app: App<Element>) {
  app.use(router)
  const token = getStorage(LocalStorageKeyConst.USER_TOKEN)
  if (token) {
    const menuInfo = await loginApi.getLoginInfo()
    // useUserStore().setUserLoginInfo(menuInfo)
    setStorage(LocalStorageKeyConst.USER_MENU_TREE, menuInfo)
  }
  eventEmitter.emit('Router:reload')
}

router.onError((error, to) => {
  const errors = ['Failed to fetch dynamically imported module']
  if (errors.some((e) => error.message.includes(e))) {
    window.location = to.fullPath
  }
})
